package com.formiaomiao.demain.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dasu.blur.DBlur;
import com.formiaomiao.demain.R;
import com.formiaomiao.demain.adapter.DataRecycleAdapter;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.model.CheckFollowBean;
import com.formiaomiao.demain.model.DemainBean;
import com.formiaomiao.demain.model.FollowBean;
import com.formiaomiao.demain.ui.PublishWindow;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.SetLeftBgUtils;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.util.UseGlideUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.formiaomiao.demain.weight.TopFloatScrollView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class DemainUserActivity extends BaseActivity implements TopFloatScrollView.OnScrollListener,
        DataRecycleAdapter.onLongItemClickListener {

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.tv_class_submit)
    TextView tvClassSubmit;
    @BindView(R.id.iv_demain_user)
    ImageView ivDemainUser;
    @BindView(R.id.iv_demain_head)
    ImageView ivDemainHead;
    @BindView(R.id.tv_demain_name)
    AppCompatTextView tvDemainName;
    @BindView(R.id.btn_demain_follow)
    Button btnDemainFollow;
    @BindView(R.id.btn_demain_news)
    Button btnDemainNews;
    @BindView(R.id.rl_user_big)
    RelativeLayout rlUserBig;
    @BindView(R.id.iv_demain_small_head)
    ImageView ivDemainSmallHead;
    @BindView(R.id.tv_demain_small_name)
    AppCompatTextView tvDemainSmallName;
    @BindView(R.id.btn_demain_small_follow)
    Button btnDemainSmallFollow;
    @BindView(R.id.btn_demain_small_news)
    Button btnDemainSmallNews;
    @BindView(R.id.rl_user_small)
    RelativeLayout rlUserSmall;
    @BindView(R.id.rc_demain_user)
    RecyclerView rcDemainUser;
    @BindView(R.id.sv_nearby_match)
    TopFloatScrollView svNearbyMatch;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.v_scroll_title)
    RelativeLayout vScrollTitle;
    @BindView(R.id.rl_search)
    RelativeLayout rlSearch;

    LoadingDialog dialog;

    private int searchLayoutTop;
    private int page = 1;
    private int userid;
    private String username = "";

    DemainBean demainBean = new DemainBean();
    List<DemainBean.DataBean.ListBean> beanList = new ArrayList<>();
    DataRecycleAdapter recycleAdapter;

    PublishWindow publishWindow;
    PopupWindow pop;

    CheckFollowBean checkFollowBean = new CheckFollowBean();    //查看是否关注
    FollowBean followBean = new FollowBean();                   //关注和取消关注操作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demain_user);
        ButterKnife.bind(this);
        ViewInit();
    }

    public void ViewInit() {
        EventBus.getDefault().register(this);
        tvClassName.setText("用户详情");
        dialog = new LoadingDialog(this);
        pop = new PopupWindow(this);
        publishWindow = new PublishWindow(this, pop);
        svNearbyMatch.setOnScrollListener(this);
        rcDemainUser.setLayoutManager(new LinearLayoutManager(this));
        recycleAdapter = new DataRecycleAdapter(this, beanList);
        rcDemainUser.setAdapter(recycleAdapter);
        recycleAdapter.setOnLongItemClickListener(this);
        DataInit();
    }

    private void DataInit() {
        userid = getIntent().getIntExtra("id", 0);
        ViewValue();
        DemainDataInit(1);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                DemainDataInit(++page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                DemainDataInit(page);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent msg) {
        if (msg.getMessage().equals("上传数据")) {
            dialog.show();
            DemainDataInit(1);
        } else if (msg.getMessage().equals("添加好友")) {
            btnDemainNews.setText("删除好友");
            btnDemainSmallNews.setText("删除好友");
        } else if (msg.getMessage().equals("删除好友")) {
            btnDemainNews.setText("加好友");
            btnDemainSmallNews.setText("加好友");
            DeleteFriendInit();
        }
    }

    private void ViewValue() {
        tvDemainName.setText(getIntent().getStringExtra("friendremarks") == null ||
                getIntent().getStringExtra("friendremarks").equals("") ?
                getIntent().getStringExtra("nickname") :
                getIntent().getStringExtra("friendremarks"));
        tvDemainSmallName.setText(getIntent().getStringExtra("friendremarks") == null ||
                getIntent().getStringExtra("friendremarks").equals("") ?
                getIntent().getStringExtra("nickname") :
                getIntent().getStringExtra("friendremarks"));
        username = getIntent().getStringExtra("username");
        UseGlideUtils.setGlide(this, getIntent().getStringExtra("head"), ivDemainHead);
        UseGlideUtils.setGlide(this, getIntent().getStringExtra("head"), ivDemainSmallHead);
        Glide.with(this).asBitmap().load(getIntent().getStringExtra("head")).into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                DBlur.source(DemainUserActivity.this, resource).
                        intoTarget(ivDemainUser).animAlpha().build().doBlurSync();
            }
        });
        if (userid == StaticValues.userid) {
            btnDemainFollow.setVisibility(View.INVISIBLE);
            btnDemainNews.setVisibility(View.INVISIBLE);
            btnDemainSmallFollow.setVisibility(View.INVISIBLE);
            btnDemainSmallNews.setVisibility(View.INVISIBLE);
        } else {
            FollowInit();
            IsFriend();
        }
    }

    /**
     * 查询是否关注
     */
    public void FollowInit() {
        btnDemainSmallFollow.setFocusable(false);
        btnDemainFollow.setFocusable(false);
        HttpParams params = new HttpParams();
        params.put("id", StaticValues.userid);
        params.put("toid", userid);
        OkGo.<String>post(BaseUrl.CHECKFOLLOW)
                .headers("Authorization", PreferenceUtils.getString(DemainUserActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                checkFollowBean = gson.fromJson(response.body(), CheckFollowBean.class);
                if (checkFollowBean.isData()) {
                    btnDemainFollow.setText("取消关注");
                    btnDemainSmallFollow.setText("取消关注");
                } else {
                    btnDemainFollow.setText("关注");
                    btnDemainSmallFollow.setText("关注");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
    }

    /**
     * 查询是否为好友
     */
    private void IsFriend() {
        btnDemainNews.setFocusable(false);
        btnDemainSmallNews.setFocusable(false);
        HttpParams params = new HttpParams();
        params.put("friendfrom", StaticValues.userid);
        params.put("friendto", userid);
        OkGo.<String>post(BaseUrl.SELECTFRIEND)
                .headers("Authorization", PreferenceUtils.getString(DemainUserActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("true")) {
                    btnDemainNews.setText("删除好友");
                    btnDemainSmallNews.setText("删除好友");
                } else {
                    btnDemainNews.setText("加好友");
                    btnDemainSmallNews.setText("加好友");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
    }

    /**
     * 关注/取消关注
     *
     * @param ischeck
     */
    private void FollowingInit(boolean ischeck) {
        dialog.show();
        String url = "";
        if (ischeck) {
            url = BaseUrl.DELETEFOLLOW;
        } else {
            url = BaseUrl.INSERTFOLLOW;
        }
        HttpParams params = new HttpParams();
        params.put("id", StaticValues.userid);
        params.put("toid", userid);
        OkGo.<String>post(url)
                .headers("Authorization", PreferenceUtils.getString(DemainUserActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                followBean = gson.fromJson(response.body(), FollowBean.class);
                if (followBean.getData().contains("成功")) {
                    EventBus.getDefault().post(new MessageEvent("上传数据"));
                }
                if (followBean.getData().equals("关注成功")) {
                    btnDemainFollow.setText("取消关注");
                    btnDemainSmallFollow.setText("取消关注");
                    checkFollowBean.setData(true);
                } else if (followBean.getData().equals("取消关注成功")) {
                    btnDemainFollow.setText("关注");
                    btnDemainSmallFollow.setText("关注");
                    checkFollowBean.setData(false);
                }
                ToastUtils.show(DemainUserActivity.this, followBean.getData());
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }

    /**
     * 获取所有动态
     */
    public void DemainDataInit(final int page) {
        HttpParams params = new HttpParams();
        params.put("id", userid);
        params.put("fromid", StaticValues.userid);
        params.put("pageNum", page);
        params.put("pageSize", 10);
        OkGo.<String>post(BaseUrl.DEMAINSELECT).headers("Authorization", PreferenceUtils.getString(DemainUserActivity.this, PreferenceValues.TOKEN)).params(params)
                .tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (page == 1) {
                    beanList.clear();
                }
                demainBean = gson.fromJson(response.body(), DemainBean.class);
                if (demainBean.getCode() == 200) {
                    beanList.addAll(demainBean.getData().getList());
                    recycleAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.show(DemainUserActivity.this, demainBean.getMsg());
                }
                dialog.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dialog.dismiss();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
            }
        });
    }

    /**
     * 点赞
     */
    private void LikeingInit(final int i, final int type) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("likeid", beanList.get(i).getDataid());
        params.put("userid", StaticValues.userid);
        params.put("type", type);
        OkGo.<String>post(BaseUrl.LIKE)
                .headers("Authorization", PreferenceUtils.getString(this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    if (beanList.get(i).getIslike() == 0) {
                        beanList.get(i).setIslike(1);
                        beanList.get(i).setLikecount(beanList.get(i).getLikecount() + 1);
                    } else {
                        beanList.get(i).setIslike(0);
                        beanList.get(i).setLikecount(beanList.get(i).getLikecount() - 1);
                    }
                    recycleAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.show(DemainUserActivity.this, "操作失败");
                }
            }

            @Override
            public void onError(Response<String> response) {

            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }

    /**
     * 删除好友
     */
    private void DeleteFriendInit() {
        HttpParams params = new HttpParams();
        params.put("friendfrom", StaticValues.userid);
        params.put("friendto", userid);
        OkGo.<String>post(BaseUrl.DELETEFRIEND)
                .headers("Authorization", PreferenceUtils.getString(this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("成功")) {
                    ToastUtils.show(DemainUserActivity.this, "删除成功");
                    btnDemainNews.setText("加好友");
                    btnDemainSmallNews.setText("加好友");
                    if (FriendDetailActivity.getInstances() != null) {
                        FriendDetailActivity.getInstances().finish();
                    }
                    if (ChatActivity.getInstance() != null) {
                        ChatActivity.getInstance().finish();
                    }
                    if (ChatSettingsActivity.getInstances() != null) {
                        ChatSettingsActivity.getInstances().finish();
                    }
                    EventBus.getDefault().post(new MessageEvent("好友关系变更"));
                } else {
                    ToastUtils.show(DemainUserActivity.this, "删除失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
            }
        });
    }

    /**
     * 添加删除好友
     */
    private void AddDeleteFriend(final String status) {
        if (status.equals("加好友")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.show(DemainUserActivity.this, "您的好友申请已发出，请等待对方确认");
                    //参数为要添加的好友的username和添加理由
                    try {
                        EMClient.getInstance().contactManager().addContact(username, "嘿！有人想加你为好友");
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        EMClient.getInstance().contactManager().deleteContact(username);
                        DeleteFriendInit();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private void showShare(int index) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("Demain");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(beanList.get(index).getContent());
        oks.setImageUrl("https://www.bmob.cn/uploads/attached/app/logo/20180711/9ede3748-9162-09e3-6b97-10c6a39565fc.png");
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl("http://demain.bmob.site/");
        // 启动分享GUI
        oks.show(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            searchLayoutTop = rlUserBig.getBottom();//获取searchLayout的顶部位置
        }
    }

    @OnClick({R.id.iv_class_back, R.id.btn_demain_follow, R.id.btn_demain_news, R.id.btn_demain_small_follow, R.id.btn_demain_small_news})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_class_back:
                finish();
                break;
            case R.id.btn_demain_follow:
                FollowingInit(checkFollowBean.isData());
                break;
            case R.id.btn_demain_news:
                AddDeleteFriend(btnDemainNews.getText().toString());
                break;
            case R.id.btn_demain_small_follow:
                FollowingInit(checkFollowBean.isData());
                break;
            case R.id.btn_demain_small_news:
                AddDeleteFriend(btnDemainSmallNews.getText().toString());
                break;
        }
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= searchLayoutTop) {
            if (rlSearch.getParent() != vScrollTitle) {
                rlUserSmall.removeView(rlSearch);
                vScrollTitle.addView(rlSearch);
                vScrollTitle.setBackgroundResource(R.mipmap.smallbg);
            } else {
            }
        } else {
            if (rlSearch.getParent() != rlUserSmall) {
                vScrollTitle.removeView(rlSearch);
                rlUserSmall.addView(rlSearch);
                vScrollTitle.setBackgroundColor(Color.parseColor("#00000000"));
            } else {
            }
        }
    }

    @Override
    public void longItemClickListener(View v, int i) {

    }

    @Override
    public void headItemClickListener(View v, int i) {

    }

    @Override
    public void shareItemClickListener(View v, int i) {
        showShare(i);
    }

    @Override
    public void msgItemClickListener(View v, final int i) {
        if (beanList.get(i).getMsgcount() == 0) {
            publishWindow.showPicPopWindow(rcDemainUser);
            publishWindow.setOnPublishClickListener(new PublishWindow.PublishClickListener() {
                @Override
                public void onPublishClickListener(View v, String data) {
                    PublishDataInit(i, beanList.get(i).getDataid(), data);
                }
            });
        } else {
            Intent intent = new Intent();
            intent.setClass(DemainUserActivity.this, DemainCommentActivity.class);
            intent.putExtra("userid", beanList.get(i).getIduser());
            intent.putExtra("name", beanList.get(i).getUserBean().getNickName());
            intent.putExtra("head", beanList.get(i).getUserBean().getUserHead());
            intent.putExtra("time", beanList.get(i).getContentDate());
            intent.putExtra("data", beanList.get(i).getContent());
            intent.putExtra("demainid", beanList.get(i).getDataid());
            ArrayList<String> imglist = new ArrayList<>();
            for (int j = 0; j < beanList.get(i).getImgBean().size(); j++) {
                imglist.add(beanList.get(i).getImgBean().get(j).getUrl());
            }
            intent.putStringArrayListExtra("imgs", imglist);
            startActivity(intent);
        }
    }

    @Override
    public void likeItemClickListener(View v, int i) {
        int type = -1;
        if (beanList.get(i).getIslike() == 0) {
            type = 1;
        } else {
            type = 0;
        }
        LikeingInit(i, type);
    }

    private void PublishDataInit(final int index, String topicid, String data) {
        dialog.show();
        HttpParams params = new HttpParams();
        params.put("topicid", topicid);
        params.put("content", data);
        params.put("fromuid", StaticValues.userid);
        OkGo.<String>post(BaseUrl.INSERTCOMMENT)
                .headers("Authorization", PreferenceUtils.getString(DemainUserActivity.this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    ToastUtils.show(DemainUserActivity.this, "评论成功");
                    beanList.get(index).setMsgcount(beanList.get(index).getMsgcount() + 1);
                    recycleAdapter.notifyDataSetChanged();
                    if (pop != null) {
                        pop.dismiss();
                    }
                } else {
                    ToastUtils.show(DemainUserActivity.this, "评论失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }
}
